<template>
	<view class="addNote">
		<WXofficialAccount bottom='100rpx'></WXofficialAccount>
		<!-- #ifdef APP -->
		<yk-authpup ref="authpup" type="top" @changeAuth="changeAuth"
			permissionID="WRITE_EXTERNAL_STORAGE"></yk-authpup>
		<!-- #endif -->

		<!-- 上传视频或者图片 -->
		<view class="up-page">
			<!--图片-->
			<view class="show-box" v-for="(item,index) in imageList" :key="index">
				<image class="full" :src="$wanlshop.oss(item)" @tap="previewImage(item)" mode="widthFix">
				</image>
				<view class="delect-icon" @click="delect(index)">
					<image class="full" :src="clearIcon" mode=""></image>
				</view>
			</view>
			<!--视频-->
			<view class="show-box" v-if="videoList != ''">
				<video class="full" :src="$wanlshop.oss(videoList)"></video>
				<view class="delect-icon" @tap="delectVideo(index1)">
					<image class="full" :src="clearIcon" mode=""></image>
				</view>
			</view>
			<!-- #ifdef APP -->
			<view v-if="VideoOfImagesShow" @tap.stop="openAuth('WRITE_EXTERNAL_STORAGE')" class="mb16 box-mode">
				<image class="full" :src="selectfile" mode=""></image>
			</view>
			<!-- #endif -->
			<!-- #ifndef APP -->
			<view v-if="VideoOfImagesShow" @tap.stop="chooseVideoImage" class="mb16 box-mode">
				<image class="full" :src="selectfile" mode=""></image>
			</view>
			<!-- #endif -->

		</view>
		<view class="error f20">
			说明：上传一条视频或9张图片
		</view>
		<view class="value mt20">
			<view class="inputBox">
				<u-input v-model="info.title" placeholder="来个醒目的标题"></u-input>
			</view>
			<view class="inputBox">
				<u-input type="textarea" height='220' auto-height v-model="info.content" placeholder="添加正文"></u-input>
			</view>

			<view class="goodsBox">
				<view class="iBox flex" v-for="i in goods" :key="i.id" v-if="goods">
					<image class="imgs" :src="$wanlshop.oss(i.image)" mode=""></image>
					<view class="ml24 flex1">
						<view class="c3 f28 overflow_2 titleBox">
							{{i.title}}
						</view>
						<view class="tar error f20 mr20">
							￥<text class="f28 fb">{{i.price}}</text>
						</view>
					</view>
				</view>
				<view class="flex_sb mt16" v-if="$store.state.user.is_shop == 1"
					@click="$wanlshop.auth('/pages/note/shopList?id='+info.goods_id.join((',')))">
					<view class="f28 c3">
						添加商品
					</view>
					<view class="">
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
			</view>

		</view>
		<view class="bottomBtn">
			<view class="cgx f24">
				<u-icon name="file-text" color="#3065FA" size="30"></u-icon>
				<text class="ml14" @click="btnSub(1)">存入草稿箱</text>
			</view>
			<button class="btn" @click="btnSub(0)" open-type="liveActivity">
				发布内容
			</button>
		</view>
	</view>
</template>

<script>
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	];
	// #ifdef APP
	import ykAuthpup from "@/components/yk-authpup/yk-authpup";
	// #endif
	export default {
		// #ifdef APP
		components: {
			ykAuthpup
		},
		// #endif
		data() {
			return {
				// 图标
				clearIcon: 'https://img.aibbyp.com/wechat/images/nHome/close.png',
				selectfile: 'https://img.aibbyp.com/wechat/images/nHome/tpsc.png',
				VideoOfImagesShow: true, // 页面图片或视频数量超出后，拍照按钮隐藏
				imageList: [], //存放图片的地址
				videoList: [], //视频存放的地址
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				sourceTypeIndex: 2,
				cameraList: [{
					value: 'back',
					name: '后置摄像头',
					checked: 'true'
				}, {
					value: 'front',
					name: '前置摄像头'
				}],
				cameraIndex: 0, //上传视频时的数量
				maxCount: 9, //图片和视频允许上传的总数

				imgType: [],
				info: {
					title: '',
					content: '',
					adcode: '',
					city: '',
					content_url: null,
					goods_id: [],
					is_draft: null,
					type: null,
					location: '',
				},
				goods: [],
				multipart: null,
				uploadurl: null,
			}
		},
		onLoad(i) {
			if (i.id) {
				this.getData(i.id)
				this.info.id = i.id
			}
			this.getMultipart()
			let address = uni.getStorageSync('address')
			if (address) {
				this.info.location = address.location.lng.toString() + ',' + address.location.lat.toString()
			}
			let userInfo = uni.getStorageSync('wanlshop:user')
			if (userInfo.userInfo && userInfo.userInfo.token) {
				this.$store.dispatch('user/getWechatSubscribe');
			}
		},
		onUnload() {
			(this.imageList = []), (this.sourceTypeIndex = 2), (this.sourceType = ['拍摄', '相册', '拍摄或相册']);
		},
		onShow() {
			this.info.goods_id = this.goods.map(a => a.id)
		},
		methods: {
			//这个是自己的方法名
			openAuth() {
				this.$refs['authpup'].open() //调起自定义权限目的弹框,具体可看示例里面很详细
			},
			//用户授权权限后的回调
			changeAuth() {
				//这里是权限通过后执行自己的代码逻辑
				console.log('权限已授权，可执行自己的代码逻辑了');
				this.chooseVideoImage()
			},
			getData(id) {
				this.$api.post({
					url: '/wanlshop.user/contentEditDetail',
					data: {
						id: id
					}
				}).then(res => {
					for (let i in this.info) {
						for (let k in res) {
							if (i == k) {
								this.info[i] = res[k]
							}
						}
					}
					console.log(this.info);
					if (this.info.type == 'image') {
						this.imageList = this.info.content_url
					}
					if (this.info.type == 'video') {
						this.videoList = this.info.content_url
					}
					this.goods = res.goods
					this.info.goods_id = res.goods.map(a => a.id)

				})
			},
			// 存入草稿箱
			async btnSub(i) {
				const shouldProceed = await this.$wanlshop.setrequestSubscribeMessage([
					'qa9cVLAWtjZ-E3DB54wlgje0JqOFLH667pr2cZqy80w',
					'164Ryc6Monn9ZENshvR09gbFejsRSAyhqOskNwN7VS4',
					'yCr7CV_XOSrpoDSSIqWxWv6fM23sykjPx0Nilj8ktms',
				])
				if (shouldProceed) {
					console.log(this.imageList);
					if (this.info.type == null) {
						uni.showToast({
							title: '请上传视频或图片',
							icon: 'none'
						})
						return
					}
					if (this.info.type == 'video') {
						if (this.videoList == '' || this.videoList == null) {
							uni.showToast({
								title: '请上传视频或图片',
								icon: 'none'
							})
							return
						} else {
							this.info.content_url = this.videoList
						}
					}
					if (this.info.type == 'image') {
						if (this.imageList.length == 0 || this.imageList == null) {
							console.log('图片');
							uni.showToast({
								title: '请上传视频或图片',
								icon: 'none'
							})
							return
						} else {
							this.info.content_url = this.imageList
						}
					}
					// if (this.info.title == '' || this.info.content == '') {
					// 	uni.showToast({
					// 		title: '请输入标题和正文',
					// 		icon: 'none'
					// 	})
					// 	return
					// }
					this.info.is_draft = i
					console.log(this.info);

					this.info.adcode = uni.getStorageSync('address').ad_info ? uni.getStorageSync('address').ad_info
						.adcode :
						''
					this.info.city = uni.getStorageSync('address').ad_info ? uni.getStorageSync('address').ad_info
						.city :
						''
					this.$api.post({
						url: '/wanlshop.user/pushContent',
						data: this.info
					}).then(res => {
						if (res) {
							uni.showToast({
								title: "保存成功",
								icon: 'none'
							})
							this.imageList = []
							this.videoList = ''
							this.info.title = ''
							this.info.content = ''
							this.info.goods_id = ''
							this.goods = []
							return
						}
					})

				}
			},
			//点击上传图片或视频
			chooseVideoImage() {
				uni.showActionSheet({
					title: '选择上传类型',
					itemList: ['图片', '视频'],
					success: res => {
						console.log(res);
						if (res.tapIndex == 0) {
							this.chooseImages();
						} else {
							this.chooseVideo();
						}
					}
				});
			},
			//上传图片
			chooseImages() {
				uni.chooseImage({
					count: this.maxCount, //允许选择的数量
					success: res => {
						console.log(res);
						for (let i in res.tempFilePaths) {
							this.myUpload(res.tempFilePaths[i], 'image')
						}
						// this.imageList = this.imageList.concat(res.tempFilePaths);
						//console.log(this.imageList)


					}
				})
			},
			//上传视频
			chooseVideo(index) {

				uni.chooseVideo({
					maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
					count: this.maxCount,
					camera: this.cameraList[this.cameraIndex].value, //'front'、'back'，默认'back'
					sourceType: sourceType[this.sourceTypeIndex],
					success: res => {
						this.myUpload(res.tempFilePath, 'video')
						return

						console.log(this.videoList);
					}
				})
			},
			//预览图片
			previewImage: function(e) {
				console.log(e)
				uni.previewImage({
					current: e,
					urls: this.imageList
				});
			},
			// 删除图片
			delect(index) {
				uni.showModal({
					title: '提示',
					content: '是否要删除该图片',
					success: res => {
						if (res.confirm) {
							this.imageList.splice(index, 1);
						}

					}
				});
			},
			// 删除视频
			delectVideo(index) {
				uni.showModal({
					title: '提示',
					content: '是否要删除此视频',
					success: res => {
						if (res.confirm) {
							this.videoList = ''
						}

					}
				});
			},


			// 获取上传限制
			getMultipart() {
				this.$api.get({
					url: '/wanlshop/common/uploadData',
				}).then(res => {
					this.multipart = res.storage == 'local' ? null : res.multipart
					this.uploadurl = res.uploadurl
				})
			},
			// 上传到线上
			myUpload(filePath, type) {
				uni.showLoading({
					title: '上传中...'
				})
				this.$api.upload({
					url: this.uploadurl,
					filePath: filePath,
					name: 'file',
					formData: this.multipart,
				}).then(res => {
					console.log('成功', res);
					uni.hideLoading()
					// 视频图片
					if (type == 'video') {
						this.videoList = res.url
						this.imageList = []
						this.info.type = 'video'
						return
					}
					if (type == 'image') {
						this.imageList.push(res.url)
						this.videoList = ''
						this.info.type = 'image'
						return
					}
					// this.videoList = this.videoList.concat(res.tempFilePath);

				}).catch(res => {
					uni.hideLoading()
				})
			},


		}
	}
</script>

<style lang="scss" scoped>
	/* 统一上传后显示的盒子宽高比 */
	.box-mode {
		width: 27vw;
		height: 27vw;

		border-radius: 8rpx;
		overflow: hidden;
	}

	.full {
		width: 100%;
		height: 100%;
	}

	.up-page {
		display: flex;
		flex-wrap: wrap;
		display: flex;
		width: 100%;

		.show-box:nth-child(3n) {
			margin-right: 0;
		}

		.show-box {
			position: relative;
			margin-bottom: 16rpx;
			margin-right: 16rpx;
			@extend .box-mode;

			.delect-icon {
				height: 40rpx;
				width: 40rpx;
				position: absolute;
				right: 0rpx;
				top: 0rpx;
				z-index: 1;
			}
		}
	}

	.addNote {
		min-height: calc(100vh - 100rpx);
		/* #ifdef MP-WEIXIN */
		min-height: calc(100vh - 0rpx);
		/* #endif */
		padding: 50rpx 32rpx 0 32rpx;
		box-sizing: border-box;
		background: #fff;

		.bottomBtn {
			position: fixed;
			bottom: 0;
			/* #ifdef H5 */
			bottom: 100rpx;
			/* #endif */
			left: 0;
			width: 100%;
			box-sizing: border-box;
			background: #fff;
			display: flex;
			align-items: center;
			padding: 22rpx 36rpx;

			.cgx {
				font-size: 24rpx;
				color: #3065FA;
			}

			.btn {
				margin-left: 36rpx;
				font-size: 28rpx;
				color: #FFFFFF;
				text-align: center;
				line-height: 62rpx;
				flex: 1;
				height: 62rpx;
				background: linear-gradient(264deg, #3065FA 0%, #3065FA 14%, #2D8DF4 99%);
				border-radius: 40rpx 40rpx 40rpx 40rpx;
			}
		}

		.goodsBox {

			margin-top: 20rpx;
			padding-bottom: 100rpx;

			.iBox {
				margin-bottom: 10rpx;
				border-bottom: 1rpx solid #ccc;

				.titleBox {
					height: 88rpx;
				}

				.imgs {
					width: 112rpx;
					height: 112rpx;
					border-radius: 10rpx;
				}
			}
		}

		.inputBox {
			padding: 0rpx 0rpx;
			border-bottom: 2rpx #eee solid;
		}

		.imgsBox {
			margin-right: 20rpx;
			position: relative;

			.cu-tag {
				position: absolute;
				right: 0;
				top: 0;
				width: 40rpx;
				height: 40rpx;
				border-radius: 28rpx;
			}
		}

		.dashed {
			border-radius: 28rpx;
			border: 1px dashed #ccc;
		}

		.bg-img {
			width: 196rpx;
			height: 196rpx;
			border-radius: 28rpx;
		}

		.value {
			height: 100%;
			background: #fff;
		}

		&:not(.u-flex-col) .value {
			margin-left: 20rpx;
		}


		&.type {
			.value ::v-deep .u-radio-group {
				flex-direction: column;
			}
		}
	}
</style>